//
//  EFADangerAddVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/11/7.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFADangerAddVC.h"
#import "EFADgrAddTitleTCell.h"
#import "EFAMatSelTCell.h"
#import "EFAMatInputTCell.h"
#import "EFAMatAddImgTCell.h"

#import <TZImagePickerController.h>
#import <TZImageManager.h>
#import "XDQiniuManager.h"
#import "ApiManager.h"
#import "GlobalHeader.h"
#import "UIColor+XDHex.h"
#import "EFAModel.h"
//#import "EFANotSelPjtVC.h"
#import "NotSelPjtVC.h"

@interface EFADangerAddVC ()<UITableViewDelegate, UITableViewDataSource, TZImagePickerControllerDelegate, EFAMatAddImgTCellDelegate>
@property (weak,   nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) UIBarButtonItem *cancelBarBtnItem;
@property (nonatomic, strong) UIBarButtonItem *publishBarBtnItem;
@property (nonatomic, strong) EFADangerPubModel *pubModel;
@end

static NSString *const kReuseTitleCellId = @"EFADgrAddTitleTCell";
static NSString *const kReuseSelCellId = @"EFAMatSelTCell";
static NSString *const kReuseInputCellId = @"EFAMatInputTCell";
static NSString *const kReuseAddImgCellId = @"EFAMatAddImgTCell";

@implementation EFADangerAddVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    self.navigationItem.title = @"新增隐患曝光";
    self.navigationItem.leftBarButtonItem = self.cancelBarBtnItem;
    self.navigationItem.rightBarButtonItem = self.publishBarBtnItem;
}

- (void)initSubViews {
    UINib *titleCellNib = [UINib nibWithNibName:kReuseTitleCellId bundle:nil];
    [self.tableView registerNib:titleCellNib forCellReuseIdentifier:kReuseTitleCellId];
    UINib *selCellNib = [UINib nibWithNibName:kReuseSelCellId bundle:nil];
    [self.tableView registerNib:selCellNib forCellReuseIdentifier:kReuseSelCellId];
    UINib *inputCellNib = [UINib nibWithNibName:kReuseInputCellId bundle:nil];
    [self.tableView registerNib:inputCellNib forCellReuseIdentifier:kReuseInputCellId];
    UINib *addImgCellNib = [UINib nibWithNibName:kReuseAddImgCellId bundle:nil];
    [self.tableView registerNib:addImgCellNib forCellReuseIdentifier:kReuseAddImgCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 67.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.alwaysBounceVertical = YES;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self refreshWholeView];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return (section == 0) ? 1 : 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        EFADgrAddTitleTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseTitleCellId forIndexPath:indexPath];
        [cell configViewWithDangerPubModel:self.pubModel];
        return cell;
    } else if (indexPath.section == 2) {
        if (indexPath.row == 0) {
            EFAMatInputTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseInputCellId forIndexPath:indexPath];
            [cell configViewWithDangerPubModel:self.pubModel];
            return cell;
        } else if (indexPath.row == 1) {
            EFAMatAddImgTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseAddImgCellId forIndexPath:indexPath];
            [cell configViewWithDangerPubModel:self.pubModel];
            cell.delegate = self;
            return cell;
        }
    }
    EFAMatSelTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseSelCellId forIndexPath:indexPath];
    [cell configViewWithDangerPubModel:self.pubModel indexPath:indexPath];
    
    return cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 14.9;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            [self jumpToSelectProject];
        } else if (indexPath.row == 1) {
            [self jumpToSelectIsFixed];
        }
    }
}

#pragma mark - EFAMatAddImgTCellDelegate
- (void)matAddImgTCell:(EFAMatAddImgTCell *)cell collectionView:(UICollectionView *)collectionView addWithIndexPath:(NSIndexPath *)cIndexPath {
    // 添加照片
    NSInteger maxCnt = self.pubModel.imgMaxCnt - self.pubModel.image_list.count;
    TZImagePickerController * pickerVC = [[TZImagePickerController alloc] initWithMaxImagesCount:maxCnt delegate:self];
    pickerVC.allowPickingVideo = NO;
    pickerVC.allowTakePicture = NO;
    pickerVC.allowPickingOriginalPhoto = NO;
    [self presentViewController:pickerVC animated:YES completion:nil];
}
- (void)matAddImgTCell:(EFAMatAddImgTCell *)cell collectionView:(UICollectionView *)collectionView delWithIndexPath:(NSIndexPath *)cIndexPath {
    [self.pubModel removePublishItemAtIndex:cIndexPath.row];
    [self refreshWholeView];
}

#pragma mark - TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    if (isSelectOriginalPhoto) {
        [assets enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            //            [[TZImageManager manager] getOriginalPhotoWithAsset:obj newCompletion:^(UIImage *photo, NSDictionary *info, BOOL isDegraded) {
            //                NSLog(@"获取原图%@， --%@, (%zd)", photos, info, isDegraded);
            //                if (!isDegraded) {
            //                    [self.pubModel addPublishItemsWithArray:@[photo]];
            //                    [self refreshWholeView];
            //                }
            //            }];
            
            // 上面一个占用内存太大，导致崩溃。所以只能考虑下面这个获取原图的方法。
            [[TZImageManager manager] getOriginalPhotoDataWithAsset:obj completion:^(NSData *data, NSDictionary *info, BOOL isDegraded) {
                NSLog(@"获取原图--%@, (%zd)", info, isDegraded);
                if (!isDegraded) {
                    if (idx < photos.count) {
                        [self.pubModel addPublishItemsWithImgArray:@[photos[idx]] originalDataArray:@[data]];
                        [self refreshWholeView];
                    }
                }
            }];
        }];
    } else {
        [self.pubModel addPublishItemsWithImgArray:photos originalDataArray:nil];
        [self refreshWholeView];
    }
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos {
    NSLog(@"选择照片缩略图 = %@", photos);
    NSLog(@"选择照片原始的assets = %@", assets);
    NSLog(@"选取照片之后的infos = %@", infos);
}

#pragma mark - event response
- (void)cancelBarBtnTapped:(UIBarButtonItem *)item {
    if (self.pubModel.isEmpty) {
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"离开该页后，编辑内容将被清空" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"离开" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[XDQiniuManager sharedInstance] cancelUpload]; //!< 如果有上传的，直接结束上传
            [self.navigationController popViewControllerAnimated:YES];
        }]];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
}
- (void)publishBarBtnTapped:(UIBarButtonItem *)item {
    // 检查用户输入信息
    if (!self.pubModel.efairyhiddendanger_title.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请输入隐患标题"];
        return;
    }
    if (!self.pubModel.efairyhiddendanger_project_id) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请选择是所属项目"];
        return;
    }
    if (!self.pubModel.efairyhiddendanger_content.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请输入隐患内容"];
        return;
    }
    
    // 图片上传成功、发布未成功的情况下，直接去发布即可
    if (self.pubModel.isImgUpload) {
        [self requestPublishDanger];
        return;
    }
    
    // 上传图片
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeAnnularDeterminate;
    hud.progress = 0;
    hud.label.text = @"上传图片...";
    
    [[XDQiniuManager sharedInstance] uploadImages:self.pubModel.imgArray progress:^(NSString *key, float percent) {
        dispatch_async(dispatch_get_main_queue(), ^{
            hud.progress = percent;
        });
    } success:^(NSArray<NSString *> *urlArray) {
        [hud hideAnimated:NO];
        [self.pubModel updateImgUrlWithArray:urlArray];
        // 发表到服务器
        [self requestPublishDanger];
        NSLog(@"开始发表到服务器");
    } failure:^(NSString *error) {
        NSLog(@"上传图片失败：%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:error];
    }];
}
#pragma mark - private methods
- (void)jumpToSelectProject {
//    EFANotSelPjtVC *vc = [[EFANotSelPjtVC alloc] init];
    NotSelPjtVC *vc =[[NotSelPjtVC alloc] init];
    vc.successHandle = ^(EFAPjtListItem  *selArray) {
        if (selArray) {
            self.pubModel.efairyhiddendanger_project_id = selArray.efairyproject_id;
            self.pubModel.efairyhiddendanger_project_name = selArray.efairyproject_name;
            [self refreshWholeView];
        }
    };
    
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    [self presentViewController:nav animated:YES completion:nil];
}
- (void)jumpToSelectIsFixed {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"隐患是否排除？" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.pubModel.efairyhiddendanger_is_fixed = YES;
        [self refreshWholeView];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.pubModel.efairyhiddendanger_is_fixed = NO;
        [self refreshWholeView];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)refreshWholeView {
    [self.tableView reloadData];
}

- (void)exitViewController {
    if (self.successHandle) {
        self.successHandle();
        self.successHandle = nil;
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - network request
- (void)requestPublishDanger {
    // 发布维护记录需要登录
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    
    // 发布帖子
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    NSMutableDictionary *pubDic = [self.pubModel yy_modelToJSONObject];
    [pubDic removeObjectForKey:@"image_list"];
    [pubDic setObject:self.pubModel.urlArray forKey:@"efairyhiddendanger_imgurl_list"];
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"efairyhiddendanger_info" : pubDic};
    
    NSLog(@"发布隐患的请求参数：%@", pars);
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiDanger] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"发布隐患返回成功：%@", responseObject);
        [hud hideAnimated:YES];
        MBProgressHUD *temp = [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"发布成功"];
        temp.completionBlock = ^{
            [self exitViewController];
        };
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"发布隐患失败：%@", error);
        [hud hideAnimated:NO];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

#pragma mark - getters and setters
- (UIBarButtonItem *)cancelBarBtnItem {
    if (!_cancelBarBtnItem) {
        _cancelBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelBarBtnTapped:)];
        NSDictionary * barItemAttributes = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_cancelBarBtnItem setTitleTextAttributes:barItemAttributes forState:UIControlStateNormal];
        NSDictionary * disableBarItemAtt = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen alpha:0.5],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_cancelBarBtnItem setTitleTextAttributes:disableBarItemAtt forState:UIControlStateDisabled];
    }
    return _cancelBarBtnItem;
}
- (UIBarButtonItem *)publishBarBtnItem {
    if (!_publishBarBtnItem) {
        _publishBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"新增" style:UIBarButtonItemStylePlain target:self action:@selector(publishBarBtnTapped:)];
        NSDictionary * barItemAttributes = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_publishBarBtnItem setTitleTextAttributes:barItemAttributes forState:UIControlStateNormal];
        NSDictionary * disableBarItemAtt = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen alpha:0.5],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_publishBarBtnItem setTitleTextAttributes:disableBarItemAtt forState:UIControlStateDisabled];
    }
    return _publishBarBtnItem;
}
- (EFADangerPubModel *)pubModel {
    if (!_pubModel) {
        _pubModel = [[EFADangerPubModel alloc] init];
//        _pubModel.efairymtrecord_device_id = self.device_id;
        _pubModel.imgMaxCnt = 9;    ///< 最多可以选择9张照片
    }
    return _pubModel;
}

@end
